﻿using B.S.Outsourcing.Domain;
using B.S.Outsourcing.ErrorCode;
using B.S.Outsourcing.Infatructrue;
using B.S.Outsourcing.Read.Api.Application.Command;
using MediatR;

namespace B.S.Outsourcing.Read.Api.Application.CommandHandler
{
    public class QueryOutsourCommandHandler : IRequestHandler<QueryOutsourCommand, ApiPaging<OutsourcingModel>>
    {
        private readonly IBaseRepository<OutsourcingModel> baseRequest;
        private readonly DBHelper1 dbHelper;

        public QueryOutsourCommandHandler(IBaseRepository<OutsourcingModel> baseRequest, DBHelper1 dbHelper)
        {
            this.baseRequest = baseRequest;
            this.dbHelper = dbHelper;
        }

        public async Task<ApiPaging<OutsourcingModel>> Handle(QueryOutsourCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiPaging<OutsourcingModel> result = new ApiPaging<OutsourcingModel>();
                var model = "select * from OutsourcingModel where OutsourcingModel.IsDelete=0";
                if (!string.IsNullOrEmpty(request.Name))
                {
                    model += $" and OutsourcingModel.Name like '%{request.Name}%'";
                }
                if (!string.IsNullOrEmpty(request.ContactPerson))
                {
                    model += $"and OutsourcingModel.ContactPerson like '%{request.ContactPerson}%'";
                }
               
                var sql = $"{model} order by OutsourcingModel.Id offset(({request.pageindex - 1})*{request.pagesize}) rows fetch next {request.pagesize} rows only";
               result.list = dbHelper.GetList<OutsourcingModel>(sql);
                result.Totalcount = result.list.Count();
                result.Totalpage = (int)Math.Ceiling(result.Totalcount * 1.0 / request.pagesize);
                return await Task.FromResult(result);
            }
            catch (Exception )
            {

                throw;
            }
        }
    }
}
